# API Docs: https://reqable.com/docs/capture/addons

from reqable import *

def save_response(url, content):
    try:
        data = {
            'url': url,
            'content': content,
            'timestamp': "1"
        }

        with open('C:\\Users\\xxx\\Desktop\\250207-jd spider\\price.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        print(f"响应已保存到price.json")
    except Exception as e:
        print(f"保存响应时出错: {e}")

def onRequest(context, request):
    # Print url to console
    # print('request url ' + context.url)

    # Update or add a query parameter
    # request.queries['foo'] = 'bar'

    # Update or add a http header
    # request.headers['foo'] = 'bar'

    # Replace http body with a text
    # request.body = 'Hello World'

    # Map with a local file
    # request.body.file('~/Desktop/body.json')

    # Convert to dict if the body is a JSON
    # request.body.jsonify()
    # Update the JSON content
    # request.body['foo'] = 'bar'

    # Done
    return request

def onResponse(context, response):
    # Update status code
    # response.code = 404

    # APIs are same as `onRequest`
    try:
        content = response.body.payload
        if '"price":' in content.lower():
            print(f"\n发现价格API: {content}")
            save_response("jd", content)
    except:
        pass


    # Done
    return response

